from . import AsyncSessionFactory
from sqlalchemy import select, delete, update
from .mcp import McpVersion, McpServer
from uuid import uuid4


async def get_mcp_version():
    async with AsyncSessionFactory() as session:
        async with session.begin():
            query = await session.execute(select(McpVersion))
            version = query.scalar()
            if not version:
                version = McpVersion()
                session.add(version)
            return version


async def get_mcp_servers():
    async with AsyncSessionFactory() as session:
        async with session.begin():
            query = await session.execute(select(McpServer))
            servers = query.scalars().all()
            return servers


async def add_mcp_servers(mcp_server: McpServer):
    async with AsyncSessionFactory() as session:
        async with session.begin():
            session.add(mcp_server)


async def update_mcp_version():
    async with AsyncSessionFactory() as session:
        async with session.begin():
            await session.execute(update(McpVersion).values(version=uuid4().hex))


async def my_delete_mcp_server(mcp_id: str):
    async with AsyncSessionFactory() as session:
        async with session.begin():
            await session.execute(delete(McpServer).where(McpServer.id == mcp_id))


async def my_get_mcp_server(mcp_id: int):
    async with AsyncSessionFactory() as session:
        async with session.begin():
            service = await session.execute(select(McpServer).where(McpServer.id == mcp_id))
            return service.scalar()


async def my_update_mcp_server(mcp_id: int, is_active: bool):
    async with AsyncSessionFactory() as session:
        async with session.begin():
            await session.execute(update(McpServer).where(McpServer.id == mcp_id).values(is_active=is_active))
